<template>
    <div id="section">
        <div style="padding-top:20px">
            <div class="card">
                <mt-datetime-picker
                  @confirm="handleDateConfirm"
                  ref="picker"
                  type="date"
                  v-model="pickerValue">
                </mt-datetime-picker>
                <div class="dateTime">
                    <span class="w1">
                        <i class="fa fa-clock-o"></i>
                        <span class="p1">日期*</span>
                    </span>
                    <span class="w1" @click="choseDate()">
                        <span>{{form.reportDateTime}}</span>
                        <i class="fa fa-caret-down" style="padding:0 5px 0 5px;"></i>
                    </span>
                </div>
            </div>
            <div class="card" style="padding-bottom:10px;">
                <div class="info">
                    <div class="headInfo">
                        <i class="fa fa-arrow-circle-o-up"></i>
                        <span class="p1">资料备份</span>
                        <span style="font-size:12px;padding-left:5px;">记录报告单（供临床医师检查）</span>
                    </div>
                    <div class="imgInfo">
                        <cube-upload
                        ref="upload"
                        :auto="ifUpload"
                        :action="action"
                        :simultaneous-uploads="1"
                        @file-submitted="fileSubmitted" 
                        @file-removed="fileRemoved"
                        @file-click="fileClick"/>
                    </div>
                </div>
            </div>
            <div class="card">
                <div class="info" style="padding-right:10px;">
                    <div class="headInfo">
                        <i class="fa fa-bars"></i>
                        <span class="p1">备注</span>
                    </div>
                    <div style="padding-top:15px;">
                        <textarea rows="4" cols="20" v-model="form.backup">
                        </textarea>
                    </div>
                </div>
            </div>
            <div class="sabeBtn">
                <p class="next" @click="saveBaseInfo">保存</p>
            </div>
        </div>
    </div>
</template>
<script>
import { MessageBox,Indicator } from "mint-ui";
import {
  uploadReportImage,
  createCaseRecord,
  updateCaseRecord,
  getCaseRecordList
} from "../../api/api";
import axios from "axios";
import qs from "qs";
export default {
  data() {
    return {
      isNewPictureReport:true,
      caseId: "",
      id: "",
      imageUrlStore: [],
      type: "",
      ifUpload: false,
      pickerValue: "",
      form: {
        reportDateTime: "请选择日期",
        backup: "",
        imageUrlStore: ""
      },
      action: {
        target: "//jsonplaceholder.typicode.com/photos/",
        prop: "base64Value"
      }
    };
  },
  methods: {
    fileClick:function(file){
      let clickImage=[];
      if(file.url.indexOf('http://www.bestckd.com/lungtest/remotewardrounds/')==-1){
        file.url.replace('blob:http://www.bestckd.com/','http://www.bestckd.com/lungtest/remotewardrounds/')
        clickImage.push(file.url);
      }else{
        clickImage.push(file.url);
      }
      this.$createImagePreview({
        imgs: clickImage
      }).show()

    },
    //添加文件后添加到数组触发
    fileSubmitted: function(file) {
      let fileLength = this.$refs.upload.files.length - 1;
      console.log("file实例======》", this.$refs.upload.files);
      if (fileLength >= 0) {
        let formData = new FormData();
        formData.append("file", this.$refs.upload.files[fileLength].file);
        formData.append("name", "file");
        formData.append("filename", "2.jpg");
        formData.append("Content-Type", "image/jpg");
        formData.append("Content-Disposition", "form-data");
        let config = {
          headers: {
            "Content-Type": "multipart/form-data;boundary = "
          }
        };
        var self = this;
        axios
          .post(
            "http://www.bestckd.com/lungtest/api/remote/upload",
            formData,
            config
          )
          .then(function(res) {
            if (res.data.IsSuccess) {
              if (self.form.imageUrlStore.length == 0) {
                self.form.imageUrlStore = res.data.Result;
              } else {
                self.form.imageUrlStore += "," + res.data.Result;
              }
              var imgNum=self.$refs.upload.files.length;
              self.$refs.upload.files[imgNum-1].serverName=res.data.Result;
              console.log('打进去数组',self.$refs.upload.files);
            }
          });
      }
    },
    //移除图片时
    fileRemoved: function(file) {
      console.log('还剩其他图片，准备删除')
      if(this.$refs.upload.files.length>1){
        if(this.form.imageUrlStore.indexOf(file.serverName)!==-1){
          var imgArray=this.form.imageUrlStore.split(',');
          console.log('删除前地状况===>',this.form.imageUrlStore);
          for(var i=0;i<imgArray.length;i++){
            if(imgArray[i]==file.serverName){
              imgArray.splice(i,1);
              this.form.imageUrlStore=imgArray.join(',')
              console.log('剩下的图片======>',this.form.imageUrlStore);
            }
          }
        }
      }else{
        console.log('不剩其他图片，准备删除')
        this.form.imageUrlStore='';
      }
    },
    //选择日期
    choseDate() {
      this.$refs.picker.open();
    },
    handleDateConfirm(val) {
      console.log(val);
      var YearNum=val.getFullYear();
      var MonthNum=val.getMonth()+1;
      var DayNum=val.getDate();
      if(MonthNum<10){
        MonthNum='0'+MonthNum
      }
      if(DayNum<10){
        DayNum='0'+DayNum
      }
      this.form.reportDateTime =
        YearNum + "-" + MonthNum + "-" + DayNum;
    },
    saveBaseInfo: function() {
      if (this.form.reportDateTime == "请选择日期") {
        MessageBox("提示", "请选择报告日期");
      } else if (this.form.backup == "" && this.form.imageUrlStore == "") {
        MessageBox("提示", "请选择报告内容填写");
      } else {
        if (this.isNewPictureReport == false) {
          this.updateCaseRecord();
        } else if (this.isNewPictureReport == true) {
          this.createCaseRecord();
        } else {
          MessageBox("提示", "创建失败");
        }
      }
    },

    updateCaseRecord: function() {
      if(this.form.reportDateTime.length==10){
        this.form.reportDateTime+=' 00:00:00'
      }
      let param = {
        Id: this.id,
        CreateTime: this.form.CreateTime,
        Type: this.type,
        Content: this.form.backup,
        PicUrls: this.form.imageUrlStore,
        CaseId: this.caseId,
        RecordTime: this.form.reportDateTime
      };
      Indicator.open({
        spinnerType: 'fading-circle'
      });  
      updateCaseRecord(param).then(res => {
        if (res.data.IsSuccess) {
          Indicator.close();
          MessageBox("提示", "更新报告成功");
          this.$router.push({
            path: "/recorddetial",
            params: { caseId: this.caseId }
          });
        }
      });
    },
    //新建报告
    createCaseRecord: function() {
      if(this.form.reportDateTime.length==10){
        this.form.reportDateTime+=' 00:00:00'
      }
      let param = {
        Type: this.type,
        Content: this.form.backup,
        PicUrls: this.form.imageUrlStore,
        CaseId: this.caseId,
        RecordTime: this.form.reportDateTime
      };
      Indicator.open({
        spinnerType: 'fading-circle'
      });
      createCaseRecord(param).then(res => {
        if (res.data.IsSuccess) {
          Indicator.close();
          MessageBox("提示", "创建报告成功");
          this.$router.push({
            path: "/recorddetial",
            params: { caseId: this.caseId }
          });
        }
      });
    },
    //添加图片验证大小
    filesAdded(files) {
      let hasIgnore = false;
      const maxSize = 1 * 1024 * 1024; // 1M
      for (let k in files) {
        const file = files[k];
        if (file.size > maxSize) {
          file.ignore = true;
          hasIgnore = true;
        }
      }
      hasIgnore &&
        this.$createToast({
          type: "warn",
          time: 1000,
          txt: "You selected >1M files"
        }).show();
    },
    //获取文件图片（更新时）
    getCaseResportImage: function() {
      if(this.form.imageUrlStore.indexOf(',')!==-1){
        this.imageUrlStore=this.form.imageUrlStore.split(',')
      }else{
        this.imageUrlStore.push(this.form.imageUrlStore);
      }
      this.showCaseResportImage();
    },
    //提取之前的报告照片加载出来
    showCaseResportImage:function(){
      var urlStart='http://www.bestckd.com/lungtest/remotewardrounds/';
      for(var i=0;i<this.imageUrlStore.length;i++){
        var img={};
        img.serverName=this.imageUrlStore[i];
        img.url=urlStart+this.imageUrlStore[i];
        this.$refs.upload.files.push(img);
      }
    },
    judegeTypeAndContent: function() {
      console.log('接收到的信息====>',this.$route.params.item)
      debugger;
      if (this.$route.params.item) {
        if (
          this.$route.params.item.RecordTime &&
          this.$route.params.item.RecordTime == "暂无数据"
        ) {
          this.type = this.$route.params.item.Type;
          this.caseId = localStorage.getItem("RecordId");
          this.isNewPictureReport = true;
        } else {
          this.isNewPictureReport = false;
          this.type = this.$route.params.item.Type;
          this.caseId = localStorage.getItem("RecordId");
          this.form.backup = this.$route.params.item.Content;
          this.id = this.$route.params.item.Id;
          this.form.imageUrlStore = this.$route.params.item.PicUrls;
          if(this.$route.params.item.RecordTime.length>10){
            this.form.reportDateTime=this.$route.params.item.RecordTime.substr(0,10)  
          }else if(this.$route.params.item.RecordTime.length==10){
            this.form.reportDateTime = this.$route.params.item.RecordTime;
          }
          if(this.form.imageUrlStore.length>0){
            this.getCaseResportImage();
          }
        }
      }
    }
  },
  mounted() {
    this.judegeTypeAndContent();
    document.getElementById("section").style.minHeight =
      localStorage.getItem("windowHeight") + "px";
    // if (this.id && this.caseId) {
    //   this.getCaseRecord();
    // }
  }
};
</script>
<style lang="scss" scoped>
#section {
  background-color: rgba(220, 220, 220, 0.2);
}
.card {
  width: 90%;
  margin: 0 auto;
  border-radius: 5px;
  background-color: white;
  margin-bottom: 30px;
  padding-left: 10px;
  .dateTime {
    height: 50px;
    line-height: 50px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    img {
      padding-right: 10px;
    }
    .w1 {
      display: flex;
      flex-direction: row;
      align-items: center;
    }
  }
  .info {
    display: flex;
    flex-direction: column;
    padding-top: 10px;
    .headInfo {
      display: flex;
      flex-direction: row;
      align-items: center;
      img {
        padding-right: 10px;
      }
    }
    textarea {
      width: 100%;
      background-color: rgba(220, 220, 220, 0.2);
      appearance: none;
      outline: none;
      border: none;
    }
    .imgInfo {
      display: flex;
      flex-direction: row;
      padding-top: 10px;
    }
  }
}
.next {
  margin: 40px auto 0;
  width: 90%;
  height: 40px;
  border-radius: 5px;
  color: white;
  text-align: center;
  line-height: 45px;
  letter-spacing: 3px;
  background-color: rgba(0, 146, 252, 0.5);
}
.p1 {
  padding-left: 5px;
}
</style>


